package com.xuecheng.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.api.client.CheckcodeClient;
import com.xuecheng.user.enums.AuthType;
import com.xuecheng.user.mapper.XcUserMapper;
import com.xuecheng.user.model.dto.AuthParamsDTO;
import com.xuecheng.user.model.dto.XcUserExt;
import com.xuecheng.user.model.po.XcUser;
import com.xuecheng.user.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: 用户名密码认证服务
 * @date 2025/2/22 12:01
 */
@Service("passwordAuthService")
@RequiredArgsConstructor
public class PasswordAuthServiceImpl implements AuthService {

    /**
     * 学成用户表mapper
     */
    private final XcUserMapper xcUserMapper;

    /**
     * 密码加密器
     */
    private final PasswordEncoder passwordEncoder;

    /**
     * 验证码客户端
     */
    private final CheckcodeClient checkcodeClient;

    /**
     * 认证方法
     *
     * @param authParamsDTO 认证参数
     * @return XcUserExt 认证通过，返回用户信息
     */
    @Override
    public XcUserExt auth(AuthParamsDTO authParamsDTO) {
        // 0. 校验验证码
        String checkcode = authParamsDTO.getCheckcode();
        String checkcodeKey = authParamsDTO.getCheckcodekey();
        Boolean verify = checkcodeClient.verify(checkcodeKey, checkcode);
        if (!verify) throw new RuntimeException("验证码错误");
        // 1. 根据用户名查询用户信息
        String username = authParamsDTO.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) throw new RuntimeException("用户不存在");
        // 2. 比对密码
        String passwordDb = xcUser.getPassword();
        if (!passwordEncoder.matches(authParamsDTO.getPassword(), passwordDb))
            throw new RuntimeException("密码错误");
        return BeanUtil.copyProperties(xcUser, XcUserExt.class);
    }

    /**
     * 获取认证类型
     *
     * @return AuthType
     */
    @Override
    public AuthType getAuthType() {
        return AuthType.PASSWORD;
    }
}
